import os
import requests
import json
import base64
import hashlib
import time
from urllib.parse import urlencode
import hmac
from datetime import datetime
from wsgiref.handlers import format_date_time
from time import mktime
import sys


class TestTask:
    def __init__(self):
        self.host = "api-dx.xf-yun.com"
        self.app_id = "ffec36e3"
        self.api_key = "264860f4b54e3108afb3869f6be3a897"
        self.api_secret = "NDM2ODgzYzU3NDNjNWMxYTNhYmU3MTJj"

    def assemble_auth_url(self, path):
        params = self.assemble_auth_params(path)
        request_url = "https://" + self.host + path
        auth_url = request_url + "?" + urlencode(params)
        return auth_url

    def assemble_auth_params(self, path):
        format_date = format_date_time(mktime(datetime.now().timetuple()))
        signature_origin = f"host: {self.host}\ndate: {format_date}\nPOST {path} HTTP/1.1"
        signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode('utf-8')
        authorization_origin = f'api_key="{self.api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha}"'
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode('utf-8')
        params = {
            "host": self.host,
            "date": format_date,
            "authorization": authorization
        }
        return params

    def test_create(self, text):
        create_path = "/v1/private/dts_create"
        auth_url = self.assemble_auth_url(create_path)
        encode_str = base64.encodebytes(text.encode("UTF8")).decode()
        headers = {'Content-Type': 'application/json'}
        data = {
            "header": {"app_id": self.app_id},
            "parameter": {
                "dts": {
                    "vcn": "x4_mingge",
                    "language": "zh",
                    "speed": 50,
                    "volume": 50,
                    "pitch": 50,
                    "rhy": 1,
                    "bgs": 0,
                    "reg": 0,
                    "rdn": 0,
                    "scn": 0,
                    "audio": {
                        "encoding": "lame",
                        "sample_rate": 16000,
                        "channels": 1,
                        "bit_depth": 16,
                        "frame_size": 0
                    },
                    "pybuf": {
                        "encoding": "utf8",
                        "compress": "raw",
                        "format": "plain"
                    }
                }
            },
            "payload": {"text": {"encoding": "utf8", "compress": "raw", "format": "plain", "text": encode_str}}
        }
        try:
            print("创建任务请求参数:", json.dumps(data))
            res = requests.post(url=auth_url, headers=headers, data=json.dumps(data))
            return res.json()
        except Exception as e:
            print("创建任务接口调用异常，错误详情:%s" % e)
            sys.exit(1)

    def test_query(self, task_id):
        query_path = "/v1/private/dts_query"
        auth_url = self.assemble_auth_url(query_path)
        headers = {'Content-Type': 'application/json'}
        data = {"header": {"app_id": self.app_id, "task_id": task_id}}
        try:
            print("\n查询任务请求参数:", json.dumps(data))
            res = requests.post(url=auth_url, headers=headers, data=json.dumps(data))
            return res.json()
        except Exception as e:
            print("查询任务接口调用异常，错误详情:%s" % e)
            sys.exit(1)

    # 新增toBase64方法
    @staticmethod
    def toBase64(audio_content):

        return base64.b64encode(audio_content).decode('utf-8')


def generate_audio_from_text(text):
    test_task = TestTask()
    # 创建任务
    task_id = test_task.test_create(text).get('header', {}).get('task_id')
    if not task_id:
        print("任务创建失败，无法生成音频")
        return None

    # 查询任务直到完成
    while True:
        time.sleep(1)
        query_result = test_task.test_query(task_id)
        code = query_result.get('header', {}).get('code')

        if code == 0:
            task_status = query_result.get('header', {}).get('task_status')

            if task_status == '5':  # 任务已完成
                audio_url = base64.b64decode(query_result['payload']['audio']['audio']).decode()
                response = requests.get(audio_url)

                # 调用 toBase64 方法将音频内容直接转换为 base64 编码
                audio_base64 = test_task.toBase64(response.content)
                print("音频生成并转换为 Base64 编码:", audio_base64)
                return audio_base64  # 返回 Base64 编码的音频内容

            else:
                print(f"任务处理中，状态码: {task_status}")
        else:
            print("任务查询失败，状态码:", code)
            return None
